__author__ = 'leeyoung'
from flask import Flask
from flask_restful import Resource, Api
import sqlite3
from flask import g
from contextlib import closing

DATABASE = 'database.db'
app = Flask(__name__)
api = Api(app)

def init_db():
    with closing(connect_db()) as db:
        with app.open_resource('schema.sql') as f:
            db.cursor().executescript(f.read())
        db.commit()

def connect_db():
    return sqlite3.connect(DATABASE)

@app.before_request
def before_request():
    g.db = connect_db()

@app.teardown_request
def teardown_request(exception):
    if hasattr(g, 'db'):
        g.db.close()

def get_connection():
    db = getattr(g, '_db', None)
    if db is None:
        db = g._db = connect_db()
    return db

def query_db(query, args=(), one=False):
    cur = get_connection().execute(query, args)
    rv = [dict((cur.description[idx][0], value)
               for idx, value in enumerate(row)) for row in cur.fetchall()]
    return (rv[0] if rv else None) if one else rv

class registSoft(Resource):
    def get(self , Serial_Number):
        print  Serial_Number
        user = query_db('select * from users where Serial_Number = ?',
                [Serial_Number], one=True)
        if user is None:
             return {'isRegistration': 'unkown'}
        else:
             print user['Serial_Number'] ,user['status']
             return {'isRegistration': user['status'] }

api.add_resource(registSoft, '/<string:Serial_Number>')

if __name__ == '__main__':
    app.run(debug=True ,host= '0.0.0.0')
